package cn.wolfcode.luowowo.service.impl;

import cn.wolfcode.luowowo.domain.Banner;
import cn.wolfcode.luowowo.query.QueryObject;
import cn.wolfcode.luowowo.repository.BannerRepository;
import cn.wolfcode.luowowo.service.IBannerService;
import cn.wolfcode.luowowo.util.DBHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Optional;

@Service
//@Transactional //事务最后处理
public class BannerServiceImpl implements IBannerService {

    @Autowired
    private BannerRepository repository;

    @Autowired
    private MongoTemplate template;


    @Override
    public Banner get(String id) {
        Optional<Banner> optional = repository.findById(id);
        if (optional != null) {
            return optional.get();
        }
        return null;
    }

    @Override
    public Page<Banner> query(QueryObject qo) {
        //List<Banner> list = repository.findAll(); //使用repostory对象查询的结果不满足带条件查询
        //使用MongoTemplate，可以满足条件查询，但是返回的是list集合，如何封装成Page对象？
        Query query = new Query();
        //PageImpl构造器的参数3：total
        long total = template.count(query, Banner.class);

        if (total == 0) {
            //总条数为0 就返回空的page回去
            return Page.empty();
        }
        //PageImpl构造器的参数2：pageable
        PageRequest pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(), Sort.Direction.DESC, "_id");
        query.with(pageable);
        //PageImpl构造器的参数1：list
        List<Banner> list = template.find(query, Banner.class);

        return new PageImpl<Banner>(list, pageable, total);
    }


    @Override
    public void saveOrUpdate(Banner banner) {
        if (!StringUtils.hasLength(banner.getId())) {
            //保存
            banner.setId(null);
            repository.save(banner);
        }else {
            Query query = new Query();
            query.addCriteria(Criteria.where("_id").is(banner.getId()));
            //更新维护的字段
            DBHelper.update(template, query, banner,
                    "title","subTitle","coverUrl",
                    "state","type","refId","sequence");
        }
        repository.save(banner);
    }



    //获得所有的type，区分游记和攻略
    @Override
    public List<Integer> getAllType() {

        return null;
    }

    //通过类型查banner集合
    @Override
    public List<Banner> queryBanner(int type) {
        Pageable of = PageRequest.of(0, 5, Sort.Direction.ASC, "sequence");
        //查询 类型为游记 ，状态为正常的前5个
        return repository.findByTypeAndState(type, Banner.STATE_NORMAL, of);
    }

}
